import random
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException

class Flow:
    def __init__(self):
        #账号密码
        self.email='jimmyj@ciandt.com'
        self.password='2100GoogleCi&t'
        self.username='jimmyj'
        #发送次数
        self.times=50
        self.driver = webdriver.Chrome()
        self.driver.get('https://flow.ciandt.com/login')

    def login(self):
        print('开始登录')
        time.sleep(2)
        self.driver.find_element(By.NAME, 'email').send_keys(self.email)
        self.driver.find_element(By.XPATH,'//button[@type="submit"]').click()
        time.sleep(2)
        self.driver.find_element(By.ID, 'identifierId').clear()
        self.driver.find_element(By.ID, 'identifierId').send_keys(self.username)
        self.driver.find_element(By.ID, 'identifierNext').click()
        time.sleep(2)
        self.driver.find_element(By.NAME, 'Passwd').send_keys(self.password)
        self.driver.find_element(By.ID, 'passwordNext').click()
        time.sleep(2)
        print('手动处理谷歌验证')
        #self.driver.find_element(By.XPATH, '//div[@data-sendmethod="SMS"]').click()
        locator = (By.XPATH, '//h1[contains(text(),"Playground")]')
        WebDriverWait(self.driver, 60*4).until(EC.element_to_be_clickable(locator))
        self.driver.find_element(*locator).click()
        time.sleep(6)
        print('登录成功，进入Chat')
        self.driver.get('https://flow.ciandt.com/chat-with-docs/')
        self.wait_for_textarea()



    # 检查文本框是否可用,在GPT没有回复完成之前，文本框是不可用的
    def textarea_enabled(self, driver):
        try:
            element = driver.find_element(By.XPATH, '//textarea')
            # 检查disabled属性
            if element.get_attribute('disabled'):
                print('文本框不可用！')
                return False
            else:
                print('文本框可用')
                return True
        except NoSuchElementException:
            print('文本框未找到')
            return False

    def wait_for_textarea(self):
        WebDriverWait(self.driver, 60).until(lambda driver: self.textarea_enabled(driver))
        time.sleep(3)

    def say_hello(self):
        self.wait_for_textarea()
        self.driver.find_element(By.XPATH,'//textarea').send_keys('我接下来会发给你很多英语句子，你收到英语句子后请将它翻译为中文句子。',Keys.ENTER)

    def send_lines(self):
        for i in range(self.times):
            print('第{}次发送'.format(i+1))
            self.wait_for_textarea()
            #随机等待2到60秒
            sleep_time=random.randint(2,60)
            print('等待{}秒'.format(sleep_time))
            time.sleep(sleep_time)
            line=self.get_a_line()
            self.driver.find_element(By.XPATH,'//textarea').send_keys(line,Keys.ENTER)

    #获取随机几行英文句子
    def get_a_line(self):
        # 打开19.txt文件，随机读取连续的1到5行非空行
        with open('19.txt', 'r', encoding='utf-8') as f:
            lines = f.readlines()
        # 过滤掉空行或只包含空白字符的行
        non_empty_lines = [line.strip() for line in lines if line.strip()]
        # 确保有足够的非空行存在
        if non_empty_lines:
            # 随机选择起始点，注意不要超出范围，使得至少有1行可以被选中
            start_index = random.randint(0, max(0, len(non_empty_lines) - 5))
            # 随机确定结束点，结束点至少是起始点+1，最多不超过起始点+4，且不超过列表长度
            end_index = start_index + random.randint(2, min(8, len(non_empty_lines) - start_index))
            # 选择连续的行
            selected_lines = non_empty_lines[start_index:end_index]
            # 将选中的行合并为一个字符串并返回
            return '\n'.join(selected_lines)
        else:
            return None
        
    def run(self):
        self.login()
        self.say_hello()
        self.send_lines()


if __name__ == '__main__':
    flow = Flow()
    flow.run()